const express = require('express');
const sqlite3 = require('sqlite3').verbose();
const http = require('http');
const socketIo = require('socket.io');
const multer = require('multer');
const cors = require('cors');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');
const path = require('path');
const fs = require('fs');

const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"]
  }
});

const PORT = process.env.PORT || 3000;
const JWT_SECRET = process.env.JWT_SECRET || 'gift-book-secret-key';

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static('public'));
app.use('/uploads', express.static('uploads'));

// 默认路由重定向到演示页面
app.get('/', (req, res) => {
  res.redirect('/demo.html');
});

// 文件上传配置
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = 'uploads';
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir);
    }
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + '-' + file.originalname);
  }
});
const upload = multer({ storage });

// 数据库初始化
const db = new sqlite3.Database('giftbook.db');

// 创建表
db.serialize(() => {
  // 用户表
  db.run(`CREATE TABLE IF NOT EXISTS users (
    id TEXT PRIMARY KEY,
    username TEXT UNIQUE,
    password TEXT,
    role TEXT DEFAULT 'user',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  )`);

  // 活动表
  db.run(`CREATE TABLE IF NOT EXISTS events (
    id TEXT PRIMARY KEY,
    user_id TEXT,
    title TEXT,
    description TEXT,
    event_date DATE,
    theme TEXT DEFAULT 'red',
    cover_image TEXT,
    status TEXT DEFAULT 'active',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users (id)
  )`);

  // 礼金记录表
  db.run(`CREATE TABLE IF NOT EXISTS gifts (
    id TEXT PRIMARY KEY,
    event_id TEXT,
    name TEXT,
    amount REAL,
    payment_method TEXT,
    note TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (event_id) REFERENCES events (id)
  )`);

  // 打印订单表
  db.run(`CREATE TABLE IF NOT EXISTS print_orders (
    id TEXT PRIMARY KEY,
    event_id TEXT,
    user_id TEXT,
    template_id TEXT,
    status TEXT DEFAULT 'pending',
    total_amount REAL,
    shipping_address TEXT,
    tracking_number TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (event_id) REFERENCES events (id),
    FOREIGN KEY (user_id) REFERENCES users (id)
  )`);

  // 套餐表
  db.run(`CREATE TABLE IF NOT EXISTS packages (
    id TEXT PRIMARY KEY,
    name TEXT,
    price REAL,
    duration INTEGER,
    features TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  )`);

  // 用户套餐表
  db.run(`CREATE TABLE IF NOT EXISTS user_packages (
    id TEXT PRIMARY KEY,
    user_id TEXT,
    package_id TEXT,
    start_date DATE,
    end_date DATE,
    status TEXT DEFAULT 'active',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users (id),
    FOREIGN KEY (package_id) REFERENCES packages (id)
  )`);

  // 设备表
  db.run(`CREATE TABLE IF NOT EXISTS devices (
    id TEXT PRIMARY KEY,
    name TEXT,
    type TEXT,
    price_per_day REAL,
    status TEXT DEFAULT 'available',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  )`);

  // 租赁订单表
  db.run(`CREATE TABLE IF NOT EXISTS rental_orders (
    id TEXT PRIMARY KEY,
    user_id TEXT,
    device_id TEXT,
    start_date DATE,
    end_date DATE,
    total_amount REAL,
    status TEXT DEFAULT 'pending',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users (id),
    FOREIGN KEY (device_id) REFERENCES devices (id)
  )`);

  // 推广员表
  db.run(`CREATE TABLE IF NOT EXISTS promoters (
    id TEXT PRIMARY KEY,
    user_id TEXT,
    level INTEGER DEFAULT 1,
    commission_rate REAL DEFAULT 0.1,
    status TEXT DEFAULT 'active',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users (id)
  )`);

  // 祝福表
  db.run(`CREATE TABLE IF NOT EXISTS blessings (
    id TEXT PRIMARY KEY,
    event_id TEXT,
    name TEXT,
    content TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (event_id) REFERENCES events (id)
  )`);

  // 多媒体资源表
  db.run(`CREATE TABLE IF NOT EXISTS media_resources (
    id TEXT PRIMARY KEY,
    event_id TEXT,
    type TEXT, -- 'video', 'image', 'audio'
    title TEXT,
    file_path TEXT,
    thumbnail_path TEXT,
    duration INTEGER, -- 视频/音频时长(秒)
    size INTEGER, -- 文件大小(字节)
    order_index INTEGER DEFAULT 0,
    is_active BOOLEAN DEFAULT 1,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (event_id) REFERENCES events (id)
  )`);

  // 插入默认数据
  db.get("SELECT COUNT(*) as count FROM packages", (err, row) => {
    if (row.count === 0) {
      db.run(`INSERT INTO packages (id, name, price, duration, features) VALUES 
        ('free', '免费版', 0, 30, '["basic_gifts", "basic_stats"]'),
        ('standard', '标准版', 99, 30, '["basic_gifts", "basic_stats", "print_service", "screen_basic"]'),
        ('premium', '高级版', 299, 30, '["basic_gifts", "basic_stats", "print_service", "screen_advanced", "lottery", "custom_bg"]')`);
    }
  });

  // 创建默认管理员账号
  db.get("SELECT COUNT(*) as count FROM users WHERE username = 'admin'", (err, row) => {
    if (row.count === 0) {
      bcrypt.hash('admin123', 10, (err, hashedPassword) => {
        if (!err) {
          db.run('INSERT INTO users (id, username, password, role) VALUES (?, ?, ?, ?)', 
            ['admin', 'admin', hashedPassword, 'admin']);
        }
      });
    }
  });

  db.get("SELECT COUNT(*) as count FROM devices", (err, row) => {
    if (row.count === 0) {
      db.run(`INSERT INTO devices (id, name, type, price_per_day) VALUES 
        ('screen_55', '55寸大屏', 'screen', 200),
        ('projector', '投影仪', 'projector', 150),
        ('speaker', '音响设备', 'audio', 100),
        ('lighting', '灯光设备', 'lighting', 80)`);
    }
  });
});

// JWT验证中间件
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ error: '访问令牌缺失' });
  }

  jwt.verify(token, JWT_SECRET, (err, user) => {
    if (err) {
      return res.status(403).json({ error: '访问令牌无效' });
    }
    req.user = user;
    next();
  });
};

// 管理员验证中间件
const requireAdmin = (req, res, next) => {
  if (req.user.role !== 'admin') {
    return res.status(403).json({ error: '需要管理员权限' });
  }
  next();
};

// API路由

// 用户认证
app.post('/api/auth/register', async (req, res) => {
  const { username, password } = req.body;
  
  try {
    const hashedPassword = await bcrypt.hash(password, 10);
    const userId = uuidv4();
    
    db.run('INSERT INTO users (id, username, password) VALUES (?, ?, ?)', 
      [userId, username, hashedPassword], function(err) {
        if (err) {
          return res.status(400).json({ error: '用户名已存在' });
        }
        
        const token = jwt.sign({ id: userId, username, role: 'user' }, JWT_SECRET);
        res.json({ token, user: { id: userId, username, role: 'user' } });
      });
  } catch (error) {
    res.status(500).json({ error: '服务器错误' });
  }
});

app.post('/api/auth/login', async (req, res) => {
  const { username, password } = req.body;
  
  db.get('SELECT * FROM users WHERE username = ?', [username], async (err, user) => {
    if (err || !user) {
      return res.status(401).json({ error: '用户名或密码错误' });
    }
    
    const validPassword = await bcrypt.compare(password, user.password);
    if (!validPassword) {
      return res.status(401).json({ error: '用户名或密码错误' });
    }
    
    const token = jwt.sign({ id: user.id, username: user.username, role: user.role }, JWT_SECRET);
    res.json({ token, user: { id: user.id, username: user.username, role: user.role } });
  });
});

// 活动管理
app.post('/api/events', authenticateToken, (req, res) => {
  const { title, description, event_date, theme, cover_image } = req.body;
  const eventId = uuidv4();
  
  db.run('INSERT INTO events (id, user_id, title, description, event_date, theme, cover_image) VALUES (?, ?, ?, ?, ?, ?, ?)',
    [eventId, req.user.id, title, description, event_date, theme, cover_image], function(err) {
      if (err) {
        return res.status(500).json({ error: '创建活动失败' });
      }
      res.json({ id: eventId, message: '活动创建成功' });
    });
});

app.get('/api/events', authenticateToken, (req, res) => {
  db.all('SELECT * FROM events WHERE user_id = ? ORDER BY created_at DESC', [req.user.id], (err, events) => {
    if (err) {
      return res.status(500).json({ error: '获取活动列表失败' });
    }
    res.json(events);
  });
});

app.get('/api/events/:id', authenticateToken, (req, res) => {
  const { id } = req.params;
  
  db.get('SELECT * FROM events WHERE id = ? AND user_id = ?', [id, req.user.id], (err, event) => {
    if (err || !event) {
      return res.status(404).json({ error: '活动不存在' });
    }
    res.json(event);
  });
});

// 礼金管理
app.post('/api/gifts', authenticateToken, (req, res) => {
  const { event_id, name, amount, payment_method, note } = req.body;
  const giftId = uuidv4();
  
  db.run('INSERT INTO gifts (id, event_id, name, amount, payment_method, note) VALUES (?, ?, ?, ?, ?, ?)',
    [giftId, event_id, name, amount, payment_method, note], function(err) {
      if (err) {
        return res.status(500).json({ error: '录入礼金失败' });
      }
      
      // 实时通知大屏更新
      io.emit('gift_added', { event_id, gift: { id: giftId, name, amount, payment_method, note } });
      res.json({ id: giftId, message: '礼金录入成功' });
    });
});

app.get('/api/gifts/:event_id', authenticateToken, (req, res) => {
  const { event_id } = req.params;
  
  db.all('SELECT * FROM gifts WHERE event_id = ? ORDER BY created_at DESC', [event_id], (err, gifts) => {
    if (err) {
      return res.status(500).json({ error: '获取礼金记录失败' });
    }
    res.json(gifts);
  });
});

// 祝福管理
app.post('/api/blessings', (req, res) => {
  const { event_id, name, content } = req.body;
  const blessingId = uuidv4();
  
  db.run('INSERT INTO blessings (id, event_id, name, content) VALUES (?, ?, ?, ?)',
    [blessingId, event_id, name, content], function(err) {
      if (err) {
        return res.status(500).json({ error: '发送祝福失败' });
      }
      
      // 实时通知大屏更新
      io.emit('blessing_added', { event_id, blessing: { id: blessingId, name, content } });
      res.json({ id: blessingId, message: '祝福发送成功' });
    });
});

app.get('/api/blessings/:event_id', (req, res) => {
  const { event_id } = req.params;
  
  db.all('SELECT * FROM blessings WHERE event_id = ? ORDER BY created_at DESC LIMIT 50', [event_id], (err, blessings) => {
    if (err) {
      return res.status(500).json({ error: '获取祝福失败' });
    }
    res.json(blessings);
  });
});

// 文件上传
app.post('/api/upload', authenticateToken, upload.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ error: '没有上传文件' });
  }
  
  res.json({ 
    filename: req.file.filename,
    url: `/uploads/${req.file.filename}`,
    message: '文件上传成功' 
  });
});

// 多媒体资源管理
app.post('/api/media', authenticateToken, upload.single('file'), (req, res) => {
  const { event_id, type, title } = req.body;
  
  if (!req.file) {
    return res.status(400).json({ error: '没有上传文件' });
  }
  
  const mediaId = uuidv4();
  const filePath = `/uploads/${req.file.filename}`;
  
  db.run('INSERT INTO media_resources (id, event_id, type, title, file_path, size) VALUES (?, ?, ?, ?, ?, ?)',
    [mediaId, event_id, type, title, filePath, req.file.size], function(err) {
      if (err) {
        return res.status(500).json({ error: '上传多媒体资源失败' });
      }
      
      res.json({ 
        id: mediaId,
        url: filePath,
        message: '多媒体资源上传成功' 
      });
    });
});

app.get('/api/media/:event_id', (req, res) => {
  const { event_id } = req.params;
  
  db.all('SELECT * FROM media_resources WHERE event_id = ? AND is_active = 1 ORDER BY order_index, created_at', 
    [event_id], (err, media) => {
      if (err) {
        return res.status(500).json({ error: '获取多媒体资源失败' });
      }
      res.json(media);
    });
});

app.put('/api/media/:id', authenticateToken, (req, res) => {
  const { id } = req.params;
  const { title, order_index, is_active } = req.body;
  
  db.run('UPDATE media_resources SET title = ?, order_index = ?, is_active = ? WHERE id = ?',
    [title, order_index, is_active, id], function(err) {
      if (err) {
        return res.status(500).json({ error: '更新多媒体资源失败' });
      }
      res.json({ message: '更新成功' });
    });
});

app.delete('/api/media/:id', authenticateToken, (req, res) => {
  const { id } = req.params;
  
  db.run('DELETE FROM media_resources WHERE id = ?', [id], function(err) {
    if (err) {
      return res.status(500).json({ error: '删除多媒体资源失败' });
    }
    res.json({ message: '删除成功' });
  });
});

// 管理员API
app.get('/api/admin/dashboard', authenticateToken, requireAdmin, (req, res) => {
  const today = new Date().toISOString().split('T')[0];
  
  // 获取统计数据
  db.get('SELECT COUNT(*) as count FROM gifts WHERE DATE(created_at) = ?', [today], (err, todayOrders) => {
    db.get('SELECT SUM(amount) as total FROM gifts WHERE DATE(created_at) >= ?', [today], (err, monthRevenue) => {
      db.get('SELECT COUNT(DISTINCT user_id) as count FROM events', (err, activeUsers) => {
        db.get('SELECT COUNT(*) as count FROM promoters', (err, promoters) => {
          res.json({
            todayOrders: todayOrders.count,
            monthRevenue: monthRevenue.total || 0,
            activeUsers: activeUsers.count,
            promoters: promoters.count
          });
        });
      });
    });
  });
});

// Socket.io连接处理
io.on('connection', (socket) => {
  console.log('用户连接:', socket.id);
  
  socket.on('join_event', (eventId) => {
    socket.join(eventId);
    console.log(`用户 ${socket.id} 加入活动 ${eventId}`);
  });
  
  socket.on('disconnect', () => {
    console.log('用户断开连接:', socket.id);
  });
});

// 启动服务器
server.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
});

// 优雅关闭
process.on('SIGINT', () => {
  console.log('正在关闭服务器...');
  db.close((err) => {
    if (err) {
      console.error('关闭数据库时出错:', err.message);
    } else {
      console.log('数据库连接已关闭');
    }
    process.exit(0);
  });
});
